# Copyright [2011] [Ilya Rudakov]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.core.exceptions import ObjectDoesNotExist
from job_manager.models import Audit, Feed
from job_manager.utils.logging_utils import getlogger

__author__ = 'irudakov'

LOG = getlogger(__name__)

def audit(**props):
    job, user, action = props['job'], props['user'], props['action']
    Audit.objects.create(job=job, user=user, action=action)

def get_job_audit(job_id):
    try:
        LOG.debug("Getting history for job id: %s" % job_id)

        job = Feed.objects.get(id=job_id)
        audit = job.audit_set.all().order_by("-date")

        LOG.debug("Job history: %s" % str(audit))
        return {"audit": audit, "job_name": job.name}
    except ObjectDoesNotExist:
        LOG.debug("Couldn't get audit info for job because it wasn't found. Job id: %s" % job_id)
        return {"audit": None, "job_name": "This job wasn't found. Sorry..."}